package com.atguigu.gmall.auth.config;

import com.atguigu.gmall.common.utils.RsaUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

@Configuration
@Data
@ConfigurationProperties(prefix = "auth.jwt")
public class JwtProperties {

    /*
        将jwt构建token需要的配置信息和秘钥初始化
     */
    String publicKeyFile;
    String privateKeyFile;
    String secret;
    int expire;
    PublicKey publicKey;
    PrivateKey privateKey;
    @PostConstruct
    public void init(){
        //基于公钥私钥文本文件初始化公钥私钥对象
        //1、判断公钥私钥文件是否存在
        try {
            File publicFile = new File(publicKeyFile);
            File privateFile = new File(privateKeyFile);
            if(!publicFile.exists() || !privateFile.exists()){
                //重新构建秘钥对文件
                RsaUtils.generateKey(publicKeyFile, privateKeyFile ,secret );
            }
            //2、使用秘钥文件 构建公钥私钥对象
            publicKey = RsaUtils.getPublicKey(publicKeyFile);
            privateKey = RsaUtils.getPrivateKey(privateKeyFile);
        } catch (Exception e) {
//            e.printStackTrace();
            throw new RuntimeException("公钥私钥构建失败");
        }

    }
}
